import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import './Library.css'

/**
 * 图库页面组件
 * 显示所有导入的照片，支持网格视图和搜索功能
 */
function Library() {
  const navigate = useNavigate()
  const [photos, setPhotos] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [searchQuery, setSearchQuery] = useState('')
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid')
  const [selectedPhotos, setSelectedPhotos] = useState<Set<string>>(new Set())

  /**
   * 加载照片列表
   */
  const loadPhotos = async () => {
    try {
      setLoading(true)
      
      if (window.photosAPI) {
        const result = await window.photosAPI.db.getPhotos({
          search: searchQuery,
          limit: 100,
          offset: 0
        })
        setPhotos(result)
      } else {
        // 开发环境模拟数据
        setPhotos([])
      }
    } catch (error) {
      console.error('加载照片失败:', error)
    } finally {
      setLoading(false)
    }
  }

  /**
   * 处理照片点击
   */
  const handlePhotoClick = (photoId: string) => {
    navigate(`/photo/${photoId}`)
  }

  /**
   * 处理照片选择
   */
  const handlePhotoSelect = (photoId: string, selected: boolean) => {
    const newSelection = new Set(selectedPhotos)
    if (selected) {
      newSelection.add(photoId)
    } else {
      newSelection.delete(photoId)
    }
    setSelectedPhotos(newSelection)
  }

  /**
   * 处理导入按钮点击
   */
  const handleImportClick = async () => {
    try {
      if (window.photosAPI) {
        const result = await window.photosAPI.dialog.openDirectory()
        if (!result.canceled && result.filePaths.length > 0) {
          navigate(`/import?folders=${encodeURIComponent(JSON.stringify(result.filePaths))}`)
        }
      }
    } catch (error) {
      console.error('打开文件夹选择对话框失败:', error)
    }
  }

  // 初始化加载
  useEffect(() => {
    loadPhotos()
  }, [searchQuery])

  return (
    <div className="library">
      {/* 工具栏 */}
      <div className="toolbar">
        <div className="toolbar-left">
          <h1 className="page-title">图库</h1>
          <span className="photo-count">
            {photos.length} 张照片
            {selectedPhotos.size > 0 && ` (已选择 ${selectedPhotos.size} 张)`}
          </span>
        </div>
        
        <div className="toolbar-center">
          <div className="search-box">
            <input
              type="text"
              placeholder="搜索照片..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
          </div>
        </div>
        
        <div className="toolbar-right">
          <div className="view-mode-toggle">
            <button
              className={`view-mode-btn ${viewMode === 'grid' ? 'active' : ''}`}
              onClick={() => setViewMode('grid')}
              title="网格视图"
            >
              ⊞
            </button>
            <button
              className={`view-mode-btn ${viewMode === 'list' ? 'active' : ''}`}
              onClick={() => setViewMode('list')}
              title="列表视图"
            >
              ☰
            </button>
          </div>
          
          <button
            className="btn-primary import-btn"
            onClick={handleImportClick}
          >
            导入照片
          </button>
        </div>
      </div>

      {/* 内容区域 */}
      <div className="library-content">
        {loading ? (
          <div className="loading-state">
            <div className="loading-spinner"></div>
            <p>正在加载照片...</p>
          </div>
        ) : photos.length === 0 ? (
          <div className="empty-state">
            <div className="empty-state-icon">📷</div>
            <h2 className="empty-state-title">还没有照片</h2>
            <p className="empty-state-description">
              点击"导入照片"按钮开始导入您的照片集合
            </p>
            <button
              className="btn-primary"
              onClick={handleImportClick}
            >
              导入照片
            </button>
          </div>
        ) : (
          <div className={`photos-container ${viewMode}`}>
            {photos.map((photo) => (
              <div
                key={photo.id}
                className={`photo-item ${selectedPhotos.has(photo.id) ? 'selected' : ''}`}
                onClick={() => handlePhotoClick(photo.id)}
              >
                <div className="photo-thumbnail">
                  <img
                    src={photo.thumbnailPath || photo.path}
                    alt={photo.name}
                    loading="lazy"
                  />
                </div>
                
                <div className="photo-info">
                  <div className="photo-name">{photo.name}</div>
                  <div className="photo-meta">
                    {photo.width} × {photo.height}
                    {photo.fileSize && ` • ${formatFileSize(photo.fileSize)}`}
                  </div>
                </div>
                
                <div className="photo-actions">
                  <input
                    type="checkbox"
                    checked={selectedPhotos.has(photo.id)}
                    onChange={(e) => {
                      e.stopPropagation()
                      handlePhotoSelect(photo.id, e.target.checked)
                    }}
                  />
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 状态栏 */}
      <div className="status-bar">
        <div className="status-left">
          <span>共 {photos.length} 张照片</span>
          {selectedPhotos.size > 0 && (
            <span>已选择 {selectedPhotos.size} 张</span>
          )}
        </div>
        
        <div className="status-right">
          <span>视图: {viewMode === 'grid' ? '网格' : '列表'}</span>
        </div>
      </div>
    </div>
  )
}

/**
 * 格式化文件大小
 */
function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B'
  
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}

export default Library